package com.wsl.sale.utils;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.database.SingleKeyDatabaseShardingAlgorithm;
import com.google.common.collect.Range;

import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * 分库算法需要实现SingleKeyDatabaseShardingAlgorithm<T>  接口  这是一个泛型接口 。T代表分库依据的字段的类型
 */

public class ShardingDataSourceUtils implements SingleKeyDatabaseShardingAlgorithm<Long> {
    /**
     * 获取数据库连接名
     * @param avaiableDatabaseNames
     * @param shardingValue
     * @return
     */
    @Override
    public String doEqualSharding(Collection<String> avaiableDatabaseNames, ShardingValue<Long> shardingValue) {
        for (String databaseName:avaiableDatabaseNames){
            if (databaseName.endsWith(shardingValue.getValue()%2+"")){
                return databaseName;
            }
        }
        throw new IllegalArgumentException();
    }

    @Override
    public Collection<String> doInSharding(Collection<String> avaiableDatabaseNames, ShardingValue<Long> shardingValue) {
        Collection<String>  result = new LinkedHashSet<>(avaiableDatabaseNames.size());
        for (Long value : shardingValue.getValues()) {
            for (String name : avaiableDatabaseNames) {
                if (name.endsWith(value%2 + "")){
                    result.add(name);
                }
            }
        }
        return result;
    }

    @Override
    public Collection<String> doBetweenSharding(Collection<String> tablesNames, ShardingValue<Long> shardingValue) {
        Collection<String> result = new LinkedHashSet<>(tablesNames.size());
        Range<Long> range = shardingValue.getValueRange();
        for (Long i= range.lowerEndpoint(); i<range.upperEndpoint();i++){
            for (String tablesName : tablesNames) {
                if(tablesName.endsWith(i % 2 +"")){
                    result.add(tablesName);
                }
            }
        }
        return result;
    }
}
